package com.autocode.codegenerate;

import com.fh.db.SqlColumn;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author qiujunda
 * @Date 17/05/2020
 * @Description
 */
public class FreeMarkerAutoCodeUtil {
    private static final String CLASS_PATH = "C:\\Users\\junqiu\\Documents\\auto_file";

    public static void autoGenerateCodeFile(String templatePath,Map<String, Object> dataMap,String templateFileName,String desFileName){
        // step1 创建freeMarker配置实例
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            configuration.setDirectoryForTemplateLoading(new File(templatePath));
            Template template = configuration.getTemplate(templateFileName);
            File docFile = new File(CLASS_PATH + "\\" + desFileName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                    out.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String templatePath= FreeMarkerAutoCodeUtil.class.getResource("/code_generate/template/fherp").getFile();
        List<SqlColumn> columns=new ArrayList<>();
        for(int i=0;i<15;i++){
            columns.add(new SqlColumn(i,"FIELD_"+i,"","字段"+i));
        }

        Map<String, Object> dataMap=new HashMap<>();
        dataMap.put("menuName1","报表平台");dataMap.put("menuName2","菜单名称xxx");
        dataMap.put("columns",columns);
        System.out.println(templatePath);
        autoGenerateCodeFile(templatePath,dataMap,"fherp-html.ftl","fherp.html");
    }

}
